package main

import "strings"

/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-12 13:36:52
 * @Description:给定一种规律 pattern 和一个字符串 s ，判断 s 是否遵循相同的规律。

这里的 遵循 指完全匹配，例如， pattern 里的每个字母和字符串 s 中的每个非空单词
之间存在着双向连接的对应规律。
示例1:

输入: pattern = "abba", s = "dog cat cat dog"
输出: true
示例 2:

输入:pattern = "abba", s = "dog cat cat fish"
输出: false
示例 3:

输入: pattern = "aaaa", s = "dog cat cat dog"
输出: false
*/
/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-12 13:37:07
 * @Description: 双向映射
 */
func wordPattern(pattern string, s string) bool {
	byte2strMap := make(map[rune]string, len(pattern))
	str2byteMap := make(map[string]rune, len(pattern))
	arr := strings.Split(s, " ")
	if len(arr) != len(pattern) {
		return false
	}
	for i, c := range pattern {
		if str, has := byte2strMap[c]; has {
			if str != arr[i] {
				return false
			}
		} else {
			byte2strMap[c] = arr[i]
		}
		if b, has := str2byteMap[arr[i]]; has {
			if b != c {
				return false
			}
		} else {
			str2byteMap[arr[i]] = c
		}

	}
	return true
}
